package com.xing.oauth.controller;

import com.xing.oauth.domain.LightUser;
import com.xing.oauth.service.LightUserService;
import com.xing.oauth.util.RedisUtil;
import org.apache.oltu.oauth2.as.issuer.MD5Generator;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl;
import org.apache.oltu.oauth2.as.request.OAuthAuthzRequest;
import org.apache.oltu.oauth2.as.request.OAuthTokenRequest;
import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.error.OAuthError;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.ResponseType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping(value = "oauth")
public class OAuthController {

    @Autowired
    private LightUserService userApi;

    @GetMapping("/authorize")
    public Object authorize(HttpServletRequest request) {
        try {
            //构建OAuth授权请求
            OAuthAuthzRequest oauthRequest = new OAuthAuthzRequest(request);

            //1.获取OAuth授权请求
            String clientId = oauthRequest.getClientId();
            //校验客户端的id是否正确
            LightUser lightUserResult = userApi.findByClientId(clientId);
            if (null == lightUserResult) {
                OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                        .setError(OAuthError.TokenResponse.INVALID_CLIENT)
                        .setErrorDescription("无效的客户端ID")
                        .buildJSONMessage();
                return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
            }

            //2.生成授权码
            String authCode = null;
            String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
            //responseType仅支持code和token
            if (responseType.equals(ResponseType.CODE.toString())) {
                OAuthIssuerImpl oAuthIssuer = new OAuthIssuerImpl(new MD5Generator());
                authCode = oAuthIssuer.authorizationCode();
                //存入缓存中 authCode-username
                RedisUtil.getRedis().set(authCode, lightUserResult.getUserName());
            }
            return new ResponseEntity(authCode, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity("内部错误", HttpStatus.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
        }
    }

    /**
     * 获取访问令牌
     *
     * @param request
     * @return
     */
    @PostMapping("accessToken")
    public Object accessToken(HttpServletRequest request) {

        try {
            //构建OAuth请求
            OAuthTokenRequest tokenRequest = new OAuthTokenRequest(request);

            //1.获取OAuth客户端id
            String clientId = tokenRequest.getClientId();
            //检验客户端id是否正确
            LightUser lightUser = userApi.findByClientId(clientId);
            if (null == lightUser) {
                OAuthResponse oAuthResponse = OAuthResponse
                        .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                        .setError(OAuthError.TokenResponse.INVALID_CLIENT)
                        .setErrorDescription("无效的客户端ID")
                        .buildJSONMessage();
                return new ResponseEntity(oAuthResponse.getBody(), HttpStatus.valueOf(oAuthResponse.getResponseStatus()));
            }

            //2.校验客户端的key是否正确

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


}

